import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeoutException;

/**
 * @Author： yu.Tan
 * @Date: 2020/8/19 14:08
 * @Description: 消费者1与消费者2处理的消息是均分的，而且消息是轮训分发的(轮训分发 round-robin)
 */
public class ProducerWorkQueue {
    private static final String WORK_QUEUE_NAME = "MQ_WORK_QUEUE";
    private static final String WORK_QUEUE_MESSAGE = "hello world!! ------> "+new Date();

    public static void main(String[] args) {
        //获取MQ连接
        Connection connection = MQConnecitonUtils.getConnection();
        //从连接中获取Channel通道对象
        Channel channel = null;

        try {
            channel = connection.createChannel();
            //创建Queue队列
            /**
             * Declare a queue
             * @see com.rabbitmq.client.AMQP.Queue.Declare
             * @see com.rabbitmq.client.AMQP.Queue.DeclareOk
             * @param queue the name of the queue  队列名称
             * @param durable true if we are declaring a durable queue (the queue will survive a server restart)：是否持久化
             * @param exclusive true if we are declaring an exclusive queue (restricted to this connection)：队列是否独占此连接
             * @param autoDelete true if we are declaring an autodelete queue (server will delete it when no longer in use)：队列不再使用时是否自动删除此队列
             * @param arguments other properties (construction arguments) for the queue ：队列参数
             * @return a declaration-confirm method to indicate the queue was successfully declared
             * */
            channel.queueDeclare(WORK_QUEUE_NAME, false, false, false, null);

            for (int i = 0; i < 10; i++) {
                StringBuilder append = new StringBuilder(WORK_QUEUE_MESSAGE).append(i);
                //发送消息
                /***
                 * 消息发布方法
                 * param1：Exchange的名称，如果没有指定，则使用Default Exchange
                 * 这里没有指定交换机，消息将发送给默认交换机，每个队列也会绑定那个默认的交换机，但是不能显 示绑定或解除绑定
                 * param2:routingKey,消息的路由Key，是用于Exchange（交换机）将消息转发到指定的消息队列
                 * param3:消息包含的属性
                 * param4：消息体
                 */
                channel.basicPublish("",WORK_QUEUE_NAME,null,append.toString().getBytes());
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (channel != null) {
                    channel.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            } finally {

            }
        }
    }
}
